package net.eearley.getco.app;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import net.eearley.getco.app.base.Key;
import net.eearley.getco.app.base.Keypad;
import net.eearley.getco.app.base.KeypadGamePiece;
import net.eearley.getco.app.base.Util;

/**
 * The Class KeypadKnight.
 */
public class KeypadKnight extends KeypadGamePiece {
	public KeypadKnight(Keypad keypad, Key key) {
		super(keypad, key);
	}

	public void setPossibleMoves(Key startKey) {
		// hardcoded way to set up the ways it can move
		this.allkeys.add(new Key(startKey.getXCoord() + 1,
				startKey.getYCoord() + 2));
		this.allkeys.add(new Key(startKey.getXCoord() + 2,
				startKey.getYCoord() + 1));
		this.allkeys.add(new Key(startKey.getXCoord() + 2,
				startKey.getYCoord() - 1));
		this.allkeys.add(new Key(startKey.getXCoord() + 1,
				startKey.getYCoord() - 2));
		this.allkeys.add(new Key(startKey.getXCoord() - 1,
				startKey.getYCoord() - 2));
		this.allkeys.add(new Key(startKey.getXCoord() - 2,
				startKey.getYCoord() - 1));
		this.allkeys.add(new Key(startKey.getXCoord() - 2,
				startKey.getYCoord() + 1));
		this.allkeys.add(new Key(startKey.getXCoord() - 1,
				startKey.getYCoord() + 2));

	}

	/**
	 * Recursive button push.
	 * 
	 * @param limit
	 *            the limit
	 * @param keys
	 *            the keys
	 * @param counter
	 *            the counter
	 * @param currentKey
	 *            the current key
	 * 
	 * @return the int
	 */
	// TODO refactor to base class and use reflection to instantiate the
	// KeypadGamePiece
	public int recursiveButtonPush(int sequenceLength,
			Map<String, List<Key>> trackingmap, AtomicInteger counter,
			KeypadGamePiece currentPiece, int vowelLimit) {
		if (sequenceLength < 1)
			return 0;
		filter(currentPiece, vowelLimit);
		if (!reachedLimit) {
			counter.getAndIncrement();
			trackingmap.put(keypad.getLabel(currentPiece.getCurrentKey()),
					currentPiece.getTotalValidKeys());
			for (Key possiblekey : currentPiece.getTotalValidKeys()) {
				Key newKey = new Key(possiblekey.getXCoord(), possiblekey
						.getYCoord());
				KeypadGamePiece newKeypadGamePiece = new KeypadKnight(
						this.keypad, newKey);
				return recursiveButtonPush(sequenceLength - 1, trackingmap,
						counter, newKeypadGamePiece, vowelLimit);

			}
		}
		return 0;
	}

	// TODO extract out to a keyboard rule
	private boolean reachedLimit;

	// TODO extract out to a keyboard rule
	private void filter(KeypadGamePiece currentPiece, int vowelLimit) {
		String label = currentPiece.getKeypad().getLabel(
				currentPiece.getCurrentKey());
		String[] vowels = { "A", "E", "I", "O", "U" };
		if (Util.matchElement(label, vowels)) {
			vowelLimit = vowelLimit - 1;
		}
		if (vowelLimit < 0)
			reachedLimit = true;

	}
}
